package com.bjpowernode.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.entity.TUserDO;
import com.bjpowernode.manager.RedisManager;
import com.bjpowernode.mapper.TUserMapper;
import com.bjpowernode.query.TUserQuery;
import com.bjpowernode.service.UserService;
import com.bjpowernode.utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TUserMapper tUserMapper;

    // 注入加密器
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private RedisManager redisManager;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public TUser loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectUserByUserName(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return tUser;
    }

    /**
     * 分页功能
     *
     * @param current
     * @return
     */
    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        // 开启分页
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 查询
        List<TUser> tUserList = tUserMapper.selectUser();
        // 封装pageInfo
        PageInfo<TUser> pageInfo = new PageInfo<>(tUserList);
        return pageInfo;
    }

    @Override
    public boolean save(TUserQuery tUserQuery) {
        tUserQuery.setCredentialsNoExpired(1);
        tUserQuery.setAccountNoExpired(1);
        tUserQuery.setAccountNoLocked(1);
        // 创建时间
        tUserQuery.setCreateTime(DateTime.now());
        // 创建人
        // 解析jwt
        String parseToken = jwtUtil.parseToken(tUserQuery.getJwt());
        TUser user = JSONUtil.toBean(parseToken, TUser.class);
        tUserQuery.setCreateBy(user.getId());
        // 编辑人
        tUserQuery.setEditTime(DateTime.now());
        // 编辑人
        tUserQuery.setEditBy(user.getId());
        // 密码加密
        tUserQuery.setLoginPwd(passwordEncoder.encode(tUserQuery.getLoginPwd()));

        // 将userquery对象的值  , 赋值到tuser
        TUser tUser = new TUser();
        // 学习一个类 , beanUtils
        // 复制的条件 : 两个字段名相同 , 类型 也相同
        BeanUtils.copyProperties(tUserQuery, tUser);

        int i = tUserMapper.insertSelective(tUser);
        return i >= 1;
    }

    @Override
    public boolean removeUserById(Integer id) {
        int delete = tUserMapper.deleteByPrimaryKey(id);
        return delete == 1;
    }

    @Override
    public int batchDeleteUsersByIds(List<Integer> ids) {
        int batch = tUserMapper.batchDeleteByIds(ids);
        return batch;
    }

    @Override
    public TUser getUserById(Integer id) {
        TUser tUser = tUserMapper.selectUserById(id);
        // TUser tUser = tUserMapper.selectByPrimaryKey(id);
        return tUser;
    }

    @Override
    public int updataUserById(TUserQuery tUserQuery) {
        TUser tUser = new TUser();
        // 复制
        BeanUtils.copyProperties(tUserQuery, tUser);

        // 获取编辑人
        String parseToken = jwtUtil.parseToken(tUserQuery.getJwt());
        TUser user = JSONUtil.toBean(parseToken, TUser.class);
        tUser.setEditBy(user.getId());
        // 设置更新时间
        tUser.setEditTime(DateTime.now());
        // 如果没有输入密码 , 不需要加密
        if (StringUtils.hasText(tUser.getLoginPwd())){
            // 密码加密
            tUser.setLoginPwd(passwordEncoder.encode(tUserQuery.getLoginPwd()));
        }
        int i = tUserMapper.updateByPrimaryKeySelective(tUser);
        return i;
    }

    @Override
    // @Async
    public void updateLoginTime(Integer id) {
        TUser tUser = new TUser();
        tUser.setId(id);
        tUser.setLastLoginTime(DateTime.now());
        tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    public List<TUserDO> findAllUser() {
        return redisManager.getData(() -> {
            return (List<TUserDO>) redisManager.getValue(Constants.REDIS_USER_OWNER_KEY);
        }, () -> {
            return tUserMapper.selectUserIdAndName();
        }, (t) -> {
            redisManager.setValue(Constants.REDIS_USER_OWNER_KEY, t, 5, TimeUnit.MINUTES);
        });
        // List<TUser> tUserList = tUserMapper.selectUserIdAndName();
        // return tUserList;
    }
}
